const EventEmitter = require('events');

class WebBluetoothService extends EventEmitter {
  constructor() {
    super();
    this.device = null;
    this.server = null;
    this.service = null;
    this.characteristic = null;
    this.isConnected = false;
    
    // 按摩椅设备特征 (需要根据实际设备调整)
    this.MASSAGE_CHAIR_SERVICE_UUID = 0xFFF0;
    this.MASSAGE_CHAIR_CHARACTERISTIC_UUID = 0xFFF1;
    
    // 设备过滤器
    this.deviceFilters = [
      { namePrefix: '按摩椅' },
      { namePrefix: 'MassageChair' },
      { namePrefix: 'MASSAGE' },
      { services: [this.MASSAGE_CHAIR_SERVICE_UUID] }
    ];
  }

  async initialize() {
    try {
      // 检查浏览器是否支持Web Bluetooth
      if (!navigator.bluetooth) {
        throw new Error('此浏览器不支持Web Bluetooth API');
      }
      
      // 检查蓝牙是否可用
      const available = await navigator.bluetooth.getAvailability();
      if (!available) {
        throw new Error('蓝牙不可用');
      }
      
      console.log('Web Bluetooth API 初始化成功');
      return true;
    } catch (error) {
      console.error('Web Bluetooth 初始化失败:', error);
      throw error;
    }
  }

  async startScanning(timeout = 10000) {
    try {
      await this.initialize();
      
      console.log('开始扫描按摩椅设备...');
      
      // 使用 requestDevice 来扫描和选择设备
      const device = await navigator.bluetooth.requestDevice({
        filters: this.deviceFilters,
        optionalServices: [this.MASSAGE_CHAIR_SERVICE_UUID]
      });

      if (device) {
        const deviceInfo = {
          id: device.id,
          name: device.name || '未知设备',
          device: device
        };
        
        console.log('发现按摩椅设备:', deviceInfo.name, deviceInfo.id);
        return [deviceInfo]; // 返回设备数组格式以保持兼容性
      }
      
      return [];
    } catch (error) {
      if (error.name === 'NotFoundError') {
        console.log('用户取消了设备选择');
        return [];
      }
      throw new Error(`扫描失败: ${error.message}`);
    }
  }

  async connectToDevice(deviceId) {
    try {
      if (!this.device) {
        // 如果没有设备，先请求设备
        const devices = await this.startScanning();
        if (devices.length === 0) {
          throw new Error('未找到设备');
        }
        this.device = devices[0].device;
      }

      console.log('连接设备:', this.device.name);

      // 连接到GATT服务器
      this.server = await this.device.gatt.connect();
      console.log('GATT服务器连接成功');

      // 获取主要服务
      this.service = await this.server.getPrimaryService(this.MASSAGE_CHAIR_SERVICE_UUID);
      console.log('获取服务成功');

      // 获取特征
      this.characteristic = await this.service.getCharacteristic(this.MASSAGE_CHAIR_CHARACTERISTIC_UUID);
      console.log('获取特征成功');

      // 启用通知
      await this.characteristic.startNotifications();
      this.characteristic.addEventListener('characteristicvaluechanged', (event) => {
        const value = event.target.value;
        const data = new Uint8Array(value.buffer);
        console.log('接收到数据:', Array.from(data).map(b => b.toString(16).padStart(2, '0')).join(' '));
        this.emit('dataReceived', Buffer.from(data));
      });

      // 监听设备断开连接
      this.device.addEventListener('gattserverdisconnected', () => {
        console.log('设备已断开连接');
        this.handleDisconnection();
      });

      this.isConnected = true;
      this.emit('connectionStateChanged', 'connected');
      
      console.log('按摩椅设备连接并配置完成');
      return true;

    } catch (error) {
      this.handleDisconnection();
      throw new Error(`连接失败: ${error.message}`);
    }
  }

  async disconnect() {
    try {
      if (this.device && this.device.gatt.connected) {
        await this.device.gatt.disconnect();
      }
      this.handleDisconnection();
      console.log('设备断开连接成功');
    } catch (error) {
      console.error('断开连接时出错:', error);
      this.handleDisconnection();
      throw new Error(`断开连接失败: ${error.message}`);
    }
  }

  handleDisconnection() {
    this.isConnected = false;
    this.device = null;
    this.server = null;
    this.service = null;
    this.characteristic = null;
    this.emit('connectionStateChanged', 'disconnected');
  }

  async sendCommand(commandBuffer) {
    try {
      if (!this.isConnected || !this.characteristic) {
        throw new Error('设备未连接');
      }

      console.log('发送指令:', Array.from(commandBuffer).map(b => b.toString(16).padStart(2, '0')).join(' '));
      
      await this.characteristic.writeValue(commandBuffer);
      console.log('指令发送成功');
      return true;

    } catch (error) {
      throw new Error(`发送指令失败: ${error.message}`);
    }
  }

  async getStatus() {
    // 发送状态查询指令或返回模拟数据
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(Buffer.from([0x59, 0x57, 0x01, 0x00, 0x00])); // 模拟状态数据
      }, 100);
    });
  }

  isDeviceConnected() {
    return this.isConnected;
  }

  // 获取已配对的设备（Web Bluetooth API限制，无法直接获取）
  async getPairedDevices() {
    try {
      // Web Bluetooth API 不支持获取已配对设备列表
      // 这里只能返回空数组
      return [];
    } catch (error) {
      console.error('获取已配对设备失败:', error);
      return [];
    }
  }
}

module.exports = WebBluetoothService;